//websocket 连接配置
import server from '../config/server'
import vue from '../main.js'
import store from '../store/index'
import pinyin from "js-pinyin"
import audioMsg from "../assets/msg.mp3";
import audioTips from "../assets/tips.mp3";

let socket = null;
const url = server.WS;
const userId = store.state.user.userId;
var time = null;

const init = () => {
    if ("WebSocket" in window) {

        // 打开一个 websocket
        var ws = new WebSocket(url + "/" + userId);

        ws.onopen = function () {
            // WebSocket 已连接上，使用 send() 方法发送数据
            if (ws.readyState == 1) {
                socket = ws;
                let message = {
                    type: 'ping',
                    data: '心跳检查'
                }
                time = setInterval(() => {
                    socket.send(JSON.stringify(message));
                }, 120000);
            }
        };

        ws.onmessage = function (evt) {
            let data = JSON.parse(evt.data);
            console.log(data);
            if (data.type == "conn") {
                console.log(data.data);
            } else if (data.type == "request") {
                let userInfo = data.data;
                if (userInfo.status == 1) {
                    vue.$notify({ type: 'success', message: userInfo.userName + "请求添加好友!" });
                    let requestFriend = store.state.requestFriend;
                    requestFriend.push(userInfo);
                    store.dispatch('asyncSaveRequest', requestFriend);
                } else if (userInfo.status == 2) {
                    vue.$notify({ type: 'success', message: userInfo.userName + "好友请求已通过" });
                    let contactList = store.state.contactList;
                    let firstChart = getFirstLetter(userInfo.userName);
                    let index = getIndexBar(firstChart);
                    let tempUser = {
                        userId: userInfo.userId,
                        userName: userInfo.userName,
                        userImg: userInfo.userImg
                    }
                    contactList[index].push(tempUser);
                    store.dispatch('asyncSaveContactList', contactList);
                } else if (userInfo.status == 3) {
                    let voice = new Audio(audioTips);
                    voice.play();
                    vue.$notify({ type: 'warning', message: userInfo.userName + "好友请求被拒绝" });
                }

            } else if (data.type == "ping") {
                console.log(data.data);
            } else if (data.type == "chat") {
                let msgData = data.data;
                if (!store.state.isChatting) {
                    let voice = new Audio(audioMsg);
                    voice.play();
                    vue.$notify({ type: 'primary', message: msgData.fromUserName + " : " + msgData.msg });
                }
                handleMessage(msgData);
            }
        };

        ws.onclose = function () {
            // 关闭 websocket
            console.log("连接已关闭...");
            socket = null;
            if (time != null) {
                clearInterval(time);
            }
        };

        ws.onerror = function () {
            console.log("连接发生错误");
            socket = null;
            if (time != null) {
                clearInterval(time);
            }
        }

        return ws;
    } else {
        // 浏览器不支持 WebSocket
        alert("您的浏览器不支持 WebSocket!");
    }
}

const getFirstLetter = character => {
    return pinyin
        .getCamelChars(character)
        .substr(0, 1)
        .toUpperCase();
}

const indexList = [
    "A",
    "B",
    "C",
    "D",
    "E",
    "F",
    "G",
    "H",
    "I",
    "J",
    "K",
    "L",
    "M",
    "O",
    "P",
    "Q",
    "R",
    "S",
    "T",
    "U",
    "V",
    "W",
    "X",
    "Y",
    "Z",
    "#"
];

//获取索引类型位置
const getIndexBar = chart => {
    let num = indexList.length - 1;
    indexList.forEach((item, index) => {
        if (item == chart) {
            num = index;
        }
    });
    //未找到分类的都视为#类型
    return num;
}

const handleMessage = msgData => {
    let list = store.state.chatList;
    //判断列表是否为空
    if (list.length > 0) {
        let exist = false;
        list.forEach(element => {
            //已有聊天信息，更新数据
            if (element.friendId == msgData.fromUserId) {
                exist = true;
                if (store.state.isChatting) {
                    msgData.read = true;
                    element.count = 0;
                } else {
                    element.count++;
                }
                element.lastMsg = msgData.msg;
                element.lastMsgTime = msgData.time;
                element.msgList.push(msgData);
            }
        });

        //没有聊天数据，增加新的聊天数据
        if (!exist) {
            let msgList = [];
            if (store.state.isChatting) {
                msgData.read = true;
            }
            msgList.push(msgData);
            let chatData = {
                count: 1,
                lastMsg: msgData.msg,
                lastMsgTime: msgData.time,
                friendId: msgData.fromUserId,
                friendUserName: msgData.fromUserName,
                friendUserImg: msgData.fromUserImg,
                msgList: msgList
            };
            if (store.state.isChatting) {
                chatData.count = 0;
            }
            list.push(chatData);
        }
    } else {
        //初始化列表数据
        let msgList = [];
        if (store.state.isChatting) {
            msgData.read = true;
        }
        msgList.push(msgData);
        let chatData = {
            count: 1,
            lastMsg: msgData.msg,
            lastMsgTime: msgData.time,
            friendId: msgData.fromUserId,
            friendUserName: msgData.fromUserName,
            friendUserImg: msgData.fromUserImg,
            msgList: msgList
        };
        if (store.state.isChatting) {
            chatData.count = 0;
        }
        list.push(chatData);
    }
    store.dispatch('asyncSaveChatList', list);
}

export default {
    init
}